<?php
/**
 * 审核 优化处理Controller
 */
namespace Common\Controller;
use Common\Controller\WahahabaseController;
class AuditparentController extends WahahabaseController {
	// 审核记录model
	public $auditHistoryModel,$auditFlowModel;
	
	// 当前处理流程
	public $function,$subfunction;
	
    function _initialize(){
        parent::_initialize();
		
		$this->auditHistoryModel = D("common/AuditHistory");
		$this->auditFlowModel = D("common/AuditFlow");
		$this->att_model = D("Common/Attachment");
		$this->roleuser_model = D("Common/RoleUser");
		$this->audituser_model = D("Common/AuditUser");
		$this->current_user_model = D("Common/Users");
		$this->getUserRole();
    }
	
	// 查询审批列表
	public function indexAuditPage($where){
		$isAudit = ",(
		CASE
			WHEN audit_status = 1 and (SELECT role_id FROM ".C('DB_PREFIX')."users WHERE id = '".session('ADMIN_ID')."') = '4'  THEN 3
			WHEN audit_status != 1 THEN 2
			WHEN audit_level = 2 AND (SELECT role_id FROM ".C('DB_PREFIX')."users WHERE id = '".session('ADMIN_ID')."') = '3' AND d.add_department = ".session('deptid')." THEN 1
			WHEN audit_level > 2 AND audit_status = 1 AND audit_level % 2 = 1 
					AND (SELECT role_id FROM ".C('DB_PREFIX')."users WHERE id = '".session('ADMIN_ID')."') = '2'
					AND (
						SELECT 2 * fd.`level` + 1
						FROM ".C('DB_PREFIX')."audit_flow_dept fd
						LEFT JOIN ".C('DB_PREFIX')."audit_flow f ON fd.flow_id = f.id
						WHERE f. FUNCTION = '".$this->function."' AND f.subfunction = '".$this->subfunction."' AND fd.department_id = ".session('deptid')." ) = d.audit_level
			THEN 1
			WHEN audit_level > 2 AND audit_status = 1 AND audit_level % 2 = 0
					AND (SELECT role_id FROM ".C('DB_PREFIX')."users WHERE id = '".session('ADMIN_ID')."') = '3'
					AND (
						SELECT 2 * fd.`level` + 2
						FROM ".C('DB_PREFIX')."audit_flow_dept fd
						LEFT JOIN ".C('DB_PREFIX')."audit_flow f ON fd.flow_id = f.id
						WHERE f. FUNCTION = '".$this->function."' AND f.subfunction = '".$this->subfunction."' AND fd.department_id = ".session('deptid').") = d.audit_level
			THEN 1
			ELSE 2
		END
		) as isaudit";
		//$where .= " AND (d.is_publish=1 OR d.add_user=".session('ADMIN_ID').") AND (deps.department_role = '".session('Role')."' OR '".session('Role')."' in (0,1,2,3))";
		// 当前登录人 20171228
        $adminId = session('ADMIN_ID');
        $adminGroup = getUserInfo($adminId);
		$where .= " AND (
            (d.is_publish = 0 AND (d.add_user = $adminId OR ((SELECT department_id FROM hzzy_users WHERE id=$adminId) = d.add_department) AND ((SELECT role_id FROM hzzy_users WHERE id=$adminId) IN('1','2','3'))))
            OR
            (d.is_publish = 1   
                AND (
                        (SELECT IFNULL(department_role,0) as `level` FROM hzzy_users u1 LEFT JOIN hzzy_department d1 ON u1.department_id = d1.id WHERE u1.id=$adminId)
                        <= 
                        (SELECT IFNULL(department_role,0) as `level` FROM hzzy_users u2 LEFT JOIN hzzy_department d2 ON u2.department_id = d2.id WHERE u2.id=d.add_user)
                )
                AND  '$adminGroup[department_role]' in ('1','2','3')
                OR ((SELECT department_id FROM hzzy_users WHERE id=$adminId) = d.add_department)
            )
            OR
            ((SELECT role_id FROM hzzy_users WHERE id=$adminId) = 0 )
        )";

		$where = $where." AND (
			d.add_user = '".session('ADMIN_ID')."'
			OR 1 = '".session('ADMIN_ID')."'
			OR (
				d.audit_status != 3 AND 
				(
					(audit_level = 2 AND (SELECT department_id FROM ".C('DB_PREFIX')."users WHERE id = '".session('ADMIN_ID')."') = d.add_department AND (SELECT role_id FROM ".C('DB_PREFIX')."users WHERE id = '".session('ADMIN_ID')."') = '3')
					OR (
						audit_level > 2 
						AND 
							CASE audit_level%2
							WHEN 1 THEN 
								(SELECT role_id FROM ".C('DB_PREFIX')."users WHERE id = '".session('ADMIN_ID')."') in ('2','4') 
								AND (SELECT 2 * fd.`level` + 1 FROM ".C('DB_PREFIX')."audit_flow_dept fd 
									LEFT JOIN ".C('DB_PREFIX')."audit_flow f ON fd.flow_id = f.id 
									WHERE f.function='".$this->function."' AND f.subfunction='".$this->subfunction."' AND fd.department_id = ".session('deptid')." ) = d.audit_level
							ELSE 
								(SELECT role_id FROM ".C('DB_PREFIX')."users WHERE id = '".session('ADMIN_ID')."') = '3' 
								AND (SELECT 2 * fd.`level` + 2 FROM ".C('DB_PREFIX')."audit_flow_dept fd 
								LEFT JOIN ".C('DB_PREFIX')."audit_flow f ON fd.flow_id = f.id 
								WHERE f.function='".$this->function."' AND f.subfunction='".$this->subfunction."' AND fd.department_id = ".session('deptid')." ) = d.audit_level
							END
					)
				)
			)
			OR (
				d.audit_status = 3 AND (
					(SELECT department_role FROM ".C('DB_PREFIX')."department WHERE id='".session('deptid')."') <= (SELECT department_role
					FROM ".C('DB_PREFIX')."audit_flow_dept fd 
					LEFT JOIN ".C('DB_PREFIX')."audit_flow f ON fd.flow_id = f.id 
					LEFT JOIN ".C('DB_PREFIX')."department dp ON dp.id = fd.department_id 
					WHERE f.function='".$this->function."' AND f.subfunction='".$this->subfunction."'
					ORDER BY fd.`LEVEL` DESC
					LIMIT 1)
				) OR (
					'".session('ADMIN_ID')."' IN (SELECT add_user FROM ".C('DB_PREFIX')."audit_history WHERE function='".$this->function."' AND subfunction='".$this->subfunction."' AND table_id = d.id)
				) OR (d.add_department = ".session('deptid').")
			)
		)";
		
		$count = $this->deal_model->alias("d")
			->field('d.*,deps.department_role role')
			->join(array(
				' LEFT JOIN (SELECT dm.id,dm.department_role,uss.id uid from '.C('DB_PREFIX').'department as dm left join '.C('DB_PREFIX').'users as uss on uss.department_id = dm.id ) deps ON deps.uid = d.add_user ',
            ))
		    ->where($where)
		    ->count();
        $page = $this->page($count, 20);
		
		$results = $this->deal_model->alias("d")
            ->field('d.*,u.real_name,f.level,h.time,de.department_name,dep.department_name department_name_first,deps.department_role role,u1.real_name as usname,DATE_ADD(h.time, INTERVAL 7 DAY) as newtime,
						(CASE 
							WHEN audit_level > 2 THEN ad.department_name
							ELSE ad1.department_name
						END) as curdept'.$isAudit)
            ->join(array(
                ' LEFT JOIN '.C('DB_PREFIX').'users u ON d.add_user = u.id',
				' LEFT JOIN '.C('DB_PREFIX').'audit_flow f ON f.function = \''.$this->function."' AND f.subfunction='".$this->subfunction."'",
				' LEFT JOIN (SELECT table_id,MAX(add_time) as time,add_user,add_department FROM (SELECT * FROM '.C('DB_PREFIX').'audit_history WHERE `function` = \''.$this->function.'\' AND subfunction = \''.$this->subfunction.'\' ORDER BY id DESC) as T GROUP BY table_id) as h ON h.table_id = d.id',
				' LEFT JOIN '.C('DB_PREFIX').'department de ON h.add_department = de.id',
				' LEFT JOIN '.C('DB_PREFIX').'users u1 ON h.add_user = u1.id ',
				' LEFT JOIN '.C('DB_PREFIX').'department dep ON dep.id = d.add_department_first ',
				' LEFT JOIN (SELECT dm.id,dm.department_role,uss.id uid from '.C('DB_PREFIX').'department as dm left join '.C('DB_PREFIX').'users as uss on uss.department_id = dm.id ) deps ON deps.uid = d.add_user ',
				
				' LEFT JOIN '.C('DB_PREFIX').'audit_flow af ON af.`function` = \''.$this->function.'\' AND af.subfunction = \''.$this->subfunction.'\' ',
				' LEFT JOIN '.C('DB_PREFIX').'audit_flow_dept afd ON af.id = afd.flow_id AND afd.`level` = floor((audit_level - 1)/2) ',
				' LEFT JOIN '.C('DB_PREFIX').'department ad ON afd.department_id = ad.id ',
				' LEFT JOIN '.C('DB_PREFIX').'department ad1 ON d.add_department = ad1.id '
				
            ))
            ->where($where)
            ->order("d.add_time DESC")
            ->limit($page->firstRow, $page->listRows)
            ->select();
            //var_dump($results);
		//exit($this->deal_model->getLastSql());
        $this->assign("page", $page->show('Admin'));
        $this->assign("results",$results);
        $current_user_role = $this->current_user_model->where('id='.session('ADMIN_ID'))->getField('role_id');
		$this->assign("current_user_role",$current_user_role);

        //dump($results);
        $this->display();
	}
	
	// 跳转新增页面
	public function add(){
		$this->display();
	}
	// 保存新建审批表单
	public function add_post(){
		if(IS_POST){
			$url = U(CONTROLLER_NAME.'/'.(I('get.fun') != NULL ? I('get.fun') : 'index'));
			$this->dataCheck();
            $data = array_merge($_POST, $this->saveData());
            if ($this->deal_model->create()!==false) {
                $result = $this->deal_model->add($data);
                if ($result!==false) {
					// 创建审批 一级流程数据
					$history = array(
						'table_id'			=> $result,
						'audit_status'		=> 1,
						'audit_reason'		=> '新建表单',
						'amount_in_words'	=> '',
						'audit_level'		=> 1
					);
					$data = array_merge($history, $this->auditAdd());
					$this->auditHistoryModel->add($data);
					$this->saveFile($result, 14);
					
                    $this->success("添加成功！", $url);
                } else {
                    $this->error("添加失败！");
                }
            } else {
                $this->error($this->deal_model->getError());
            }
        }
	}
	
	// 跳转查看画面
    public function view(){
		// 获取基础数据
		$id = I('get.id',0,'intval');
        $result = $this->deal_model->where(array("id"=>$id))->find();
        $results = $this->att_model->where(array("table_id"=>$id, "belong_to"=>14))->select();
        $this->assign("results", $results);
				
		// 判断工程款支付报审
		if($this->function == 'payment' && $this->subfunction == "1"){
			if($result['audit_level'] < 4){
				$result = array_merge($result, $this->getTotalPrice($id));
			}
			if($result['audit_level'] > 4 && $result['audit_level'] < 6){
				$result = array_merge($result, $this->getTotalPrice($id, 2));
			}
		}
        $this->assign("result", $result);
				
		$isAudit = '1';
		// 验证当前登录人是否有审批权限
		if($result['audit_level'] == 2 && $result['add_department'] == session('deptid') && session('Role') == 3){
			$isAudit = '2';
		} elseif($result['audit_level'] > 2) {
			// 查询当前审批部门
			$auditdept = $this->auditFlowModel->alias("a")
							->field("d.department_id")
							->join(array(
								' LEFT JOIN '.C('DB_PREFIX').'audit_flow_dept d ON d.flow_id = a.id'
							))
							->where(array(
								'a.function' 	=> $this->function,
								'a.subfunction'	=> $this->subfunction,
								'd.`level`'		=> intval(($result['audit_level'] - 1)/2)
							))
							->find();
			///5555555555555555555555
			
			/*echo '<pre>';
			print_r($users);die;*/
			//$name = array_column($users, 'user_id');
			/*foreach($users as $key=>$value){
				foreach($value as $v){
					 echo $v."<br />";
				}
			}*/
			
			//var_dump($admin_id);die;
			/*echo '<pre>';
			var_dump($users['user_id']);*/
			/*if((intval($result['audit_level'])%2 == 1 && $auditdept['department_id'] == session("deptid") && $user['user_id'] == 2 )
					OR(intval($result['audit_level'])%2 == 0 && $auditdept['department_id'] == session("deptid") && session("Role") == 3 )){
				$isAudit = '2';
			}*/
			if((intval($result['audit_level'])%2 == 1 && $auditdept['department_id'] == session("deptid") && session("Role") == 2 )
					OR(intval($result['audit_level'])%2 == 0 && $auditdept['department_id'] == session("deptid") && session("Role") == 3 )){
				$isAudit = '2';
			}
		}
		$this->assign("isAudit", $isAudit);
		//dump($isAudit);
		// 循环查询审核意见
		$auditLevel = $this->getAuditFlowLevel();
		//var_dump($auditLevel);die;
		$auditResult = array();
		if($auditLevel > 2){
			for($i = 3; $i < $auditLevel; $i += 2){
				$auditResult[$i] = $this->auditHistoryModel->where(array('function' => $this->function, 'subfunction' => $this->subfunction, 'audit_level' => $i, 'table_id' => $id))->order("add_time DESC")->select();
			}
		}
		$this->assign("audit", $auditResult);
		//var_dump($auditResult);
		// 判断最终状态是否为驳回
		if($result['audit_status'] == '2'){
			// 查询驳回原因
			$returnMsg = $this->auditHistoryModel->where(array('function' => $this->function, 'subfunction' => $this->subfunction, 'table_id' => $id))->order("add_time DESC")->find();
			$this->assign("reject", $returnMsg);
		}
		
		$sc = M("SubcontractContent")->where("table_id = ".$id)->select();
		$this->assign("sc", $sc);
		
		// 验证审批权限
		$this->display();
	}
	
	// 查询总报价
	public function getTotalPrice($id, $type = 1){
		$where = array(
			'payment_review_id' => $id,
			'item_name'			=> '总报价[一+二]',
			'is_publish'		=> '1'
		);
		$price = $this->PSummary_model->field("report_construction_amount,approved_total_amount")->where($where)->find();
		if($type == 1){
			$result['supervision_amount'] = $price['approved_total_amount'] != NULL ? $price['approved_total_amount']*0.75 : 0.00;
			$result['supervision_amount_words'] = $this->number2chinese($result['supervision_amount'], true, false);
		} else {
			$result['agent_construction_amount'] = $price['approved_total_amount'] != NULL ? $price['approved_total_amount']*0.75 : 0.00;
			$result['agent_construction_amount_words'] = $this->number2chinese($result['agent_construction_amount'], true, false);
		}
		return $result;
	}
	
	// 保存审批意见
	public function audit_post(){
		if(IS_POST){
			$url = U(CONTROLLER_NAME.'/'.(I('get.fun') != NULL ? I('get.fun') : 'index'));
            $data = array_merge($_POST, $this->auditAdd());
            //var_dump($data);
            if ($this->auditHistoryModel->create()!==false) {
                $result = $this->auditHistoryModel->add($data);
                if ($result!==false) {					
					// 修改修改主表当前处理层级+1
					// ->count();
					// 
					$update = array(
						'id'			=> $data['table_id'],
						'audit_level'	=> $data['audit_status'] == 1 ? intval($data['audit_level']) + 1 : intval($data['audit_level']) - 1,
						'audit_status'	=> $data['audit_status'] == 2 ? 2 : (intval($this->getAuditFlowLevel()) == intval($data['audit_level']) ? 3 : 1)
					);
					$update = array_merge($_POST, $update);
					$this->deal_model->save($update);
					
                    $this->success("保存成功！", $url);
                } else {
                    $this->error("保存失败！");
                }
            } else {
                $this->error($this->auditHistoryModel->getError());
            }
        }
	}
	
	// 获取当前审批流程的总审核层级
	private function getAuditFlowLevel(){
		$result = $this->auditFlowModel
				->where(array(
					'function'		=> $this->function,
					'subfunction'	=> $this->subfunction,
				))
				->getField("level", true);
		return (intval(($result[0] != '' ? $result[0] : 0)) + 1) * 2;
	}
	
	// 审核表基础字段
	public function auditAdd(){
		$audit = array(
			'function'		=> $this->function,
			'subfunction'	=> $this->subfunction,
		);
		return array_merge($audit, $this->saveData());
	}
	
	// 查看审核历史列表
	public function auditHistory(){
		$where = array(
			'a.function'		=> $this->function,
			'a.subfunction'	=> $this->subfunction,
			'a.table_id'		=> I('get.id', 0, 'intval')
		);
		$audit = $this->auditHistoryModel->alias("a")
			->field("a.*,u.real_name,d.department_name,f.level")
			->join(array(
				' LEFT JOIN '.C('DB_PREFIX').'users u ON a.add_user = u.id',
				' LEFT JOIN '.C('DB_PREFIX').'department d ON a.add_department = d.id',
				' LEFT JOIN '.C('DB_PREFIX').'audit_flow f ON f.function = \''.$this->function."' AND f.subfunction='".$this->subfunction."'"
			))
			->where($where)
			->order("a.add_time ASC")
			->select();
		$this->assign("audits", $audit);
		
		$this->display();
	}
	
	// 查询当前用户类型
	public function getUserRole(){
		$user = D("Common/Users")->alias("u")
				->field("u.role_id,d.department_role as role")
				->join(array(
					' LEFT JOIN '.C('DB_PREFIX').'department d ON d.id = u.department_id'
				))
				->where(array('u.id' => session("ADMIN_ID")))
				->find();
				
		$this->assign('userrole', $user);
	}
	//
	public function add_distribution(){
		$id = $_POST['code_id'];
		//var_dump($id);
		//编辑权用户的user_id
		//var_dump($_POST['level']);
		$check1 = $_POST['check1'];
		//审核权用户的user_id
		$check2 = $_POST['check2'];
		$function = $this->function;
		$subfunction = $this->subfunction;
		$num1 = count($check1);
		$num2 = count($check2);
		//var_dump($num2);
		$data = array(
			"role_id" => 2,
			'function' => $function,
			'subfunction' => $subfunction,
			'code_id' => $id,
			'checked_num' => $num1,
			'already_num' => 0,
			'audit_level' => $_POST['level'],
			'status' => 0
		);
		$result1 = $this->roleuser_model->add($data);
		//编辑权限的用户 id
			$uid1 = $this->roleuser_model
						->field('id')
						->where(array("role_id"=>2,"function"=>$function,"subfunction" => $subfunction,"code_id" =>$id))
						->find();
			//var_dump($uid2);
			foreach($check1 as $key => $vo){
				$sub = array(
					'id'	=> $uid1["id"],
					'user_id'=> $vo
				);
				$result1_user = $this->audituser_model->add($sub);
			}

			$data['role_id'] = 3;
			$data['checked_num'] = $num2;
			$result2 = $this->roleuser_model->add($data);
			//审核权限的用户 id
			$uid2 = $this->roleuser_model
						->field('id')
						->where(array("role_id"=>3,"function"=>$function,"subfunction" => $subfunction,"code_id" =>$id))
						->find();
			//$id2 = $model->add($data);
			foreach($check2 as $key => $vo){
				$sub = array(
					'id'	=> $uid2["id"],
					'user_id'=> $vo
				);
				$result2_user = $this->audituser_model->add($sub);
			}
			//$result2 = $this->audituser_model->add($sub);
			if($result1&&$result2){

			    $this->success("保存成功！",U(CONTROLLER_NAME.'/'.(I('get.fun') != NULL ? I('get.fun') : 'index')));
	                } else {
	                $this->error("保存失败！");
	        }
			
	    
/*
		foreach($_POST['check1'] as $v){
			$data1 = array("code_id" => $_POST['code_id'],
						     "user_id" => $v,
						     "process_id"=> $_POST['code_id'],
						     "low_status" => '0',
						     "role_id"  => '2'

				);
		}
		//分配的审核权用户信息
		$data2 = array("code_id" => $_POST['code_id'],
					     "user_id" => $check2,
					     "process_id"=> $_POST['code_id'],
					     "low_status" => '0',
					     "role_id"  => '3'

			); 
		$this->roleuser_model->add($data1);*/
		//$this->roleuser_model->add($data2);
		//$url = U(CONTROLLER_NAME.'/'.(I('get.fun') != NULL ? I('get.fun') : 'index'));
		/*$result1 = $this->roleuser_model->add($data1);
		$result2 = $this->roleuser_model->add($data2);
        if($result1){

		    $this->success("保存成功！");
                } else {
                $this->error("保存失败！");
        }*/
	}
}